<template>
    <div class="inline-container">
        <template v-if="type == 'text'">
            <div style="width:100%;display:inline-table;">
                <div class="el-input__prepend">
                    <slot name="prepend"></slot>
                </div>
                <div class="el-input--outer">
                    <input type="text" class="el-input" :class="inputClass" :value="value" @input="handleInput($event)"
                        v-on="clearListeners($listeners)" v-bind="$attrs" />
                    <span class="el-input--suffix" v-if="showClearable">
                        <Icon name="close" class="el-input__icon" @click="clearText"></Icon>
                    </span>
                </div>
                <div class="el-input__append">
                    <slot name="append"></slot>
                </div>
            </div>
        </template>
        <template v-else-if="type == 'textarea'">
            <textarea class="el-textarea" :value="value" @input="handleInput($event)" v-on="clearListeners($listeners)"
                v-bind="$attrs" />
        </template>

    </div>
</template>

<script>
import { computed, defineComponent } from 'vue-demi'
import Icon from '../icon/index.vue';
export default defineComponent({
    name: "el-input",
    props: {
        value: {
            // 扩展 v-model 语法糖，所必需的props属性。需要与emit("input")配合
            type: String,
            default: ""
        },
        type: {
            // 输入框类型 [文本，多行文本]
            type: String,
            validator: value => ["text", "textarea"].includes(value),
            default: "text"
        },
        clearable: {
            // 是否添加 清空输入内容 按钮
            type: Boolean,
            default: false
        }
    },
    setup(props, { emit,slots }) {
        const handleInput = (e) => {
            // 扩展 v-model 语法糖
            emit("input", e.target.value);
        };
        const clearListeners = ($listeners) => {
            // 不加下面这句的话，父组件的 @input事件也会被继承添加到当前input元素上
            // 所以，会造成触发两次 input 事件
            // 即 @input(event)=>{this.mes = $event}
            delete $listeners.input;
            return $listeners;
        };
        const clearText = () => {
            emit("input", "")
        }
        const showClearable = computed(() => props.clearable && props.value)
        const inputClass = computed(()=>{
            return {
                'is-prepend':slots.prepend,
                'is-append':slots.append,
            }
        })
        return {
            handleInput,
            clearListeners,
            clearText,
            showClearable,
            inputClass
        };
    },
    components: { Icon }
})
</script>

<style lang="scss">
@import "./index.scss";
</style>